<?php

namespace App\Http\Controllers;

use App\Models\Coupons;
use App\Models\Member;
use App\Models\MemberCoupon;
use App\Models\Setting;
use App\Models\Staffs;
use App\Util\Qrcode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ScanController extends Controller
{
    private $_member_id = 0;
    private $Qrcode = null;

    public function index(Request $request)
    {
        if(!test_wechat()) {
            // '不是手机微信打开的';
            $_result = array('message'=>'请使用微信浏览器访问','code'=>402);
        } else {
            // 登录
            $this->login($request);
            $this->Qrcode = new Qrcode();
            $_result = array();
            switch ($request->scan_type) {
                // 员工申请
                case 'apply_staff':
                    $_result = $this->applyStaff($request);
                    break;
                // 卡券核销
                case 'check_coupon':
                    $_result = $this->checkCoupon($request);
                    break;
                case 'apply_manage':
                    $_result = $this->applyManage($request);
                    break;
            }
        }

        return view('scan',[
            'data' => $_result,
            'script' => $this->wechatJs()
        ]);
    }

    private function wechatJs()
    {
        $Wechat = $this->wechat();
        $_data = $Wechat->jssdk->buildConfig(
            ['onMenuShareTimeline','onMenuShareAppMessage','updateAppMessageShareData','updateTimelineShareData','chooseWXPay','hideMenuItems','getLocation','scanQRCode','hideAllNonBaseMenuItem','showMenuItems'],
            false,
            false,
            true
        );
        $_script = "<script src='//res.wx.qq.com/open/js/jweixin-1.6.0.js'></script>";
        $_script .= "<script>wx.config(".$_data.")</script>";
        $_script .= "<script>wx.hideAllNonBaseMenuItem()</script>";
        return $_script;
    }

    /**
     *登录
     */
    private function login($request)
    {
        $Wechat = $this->wechat();
        if($request->session()->get('scan_member_id')) {
            $this->_member_id = $request->session()->get('scan_member_id');
        } else {
            if ($request->state && $request->code) {
                $Fans = $Wechat->oauth->userFromCode($request->code);
                if(!$Member = Member::where('openid',$Fans->getId())->first()) {
                    $Member = Member::create([
                        'nickname' => $Fans->getNickname(),
                        'avatar' => $Fans->getAvatar(),
                        'openid' => $Fans->getId()
                    ]);
                }
                $this->_member_id = $Member->id;
                session(['scan_member_id'=>$Member->id]);
            } else {
                header("Location: {$Wechat->oauth->scopes(['snsapi_userinfo'])->redirect($request->fullUrl())}");
            }
        }
    }

    /**
     * 申请员工
     */
    private function applyStaff($request)
    {
        DB::beginTransaction();
        try {
            if($this->_member_id == $request->boss) {
                throw new \PDOException("不能申请成为自己的员工",402);
            }
            $_params = array(
                "boss"=>$request->boss,
                "scan_type"=>$request->scan_type,
                "uniqid" => $request->uniqid
            );
            if(!$this->Qrcode->checkParams($_params)) {
                throw new \PDOException("二维码失效", 402);
            }
            $Staff = Staffs::where("boss",$request->boss)
                ->where("member_id",$this->_member_id)
                ->withTrashed()
                ->select('status','id','deleted_at')
                ->first();
            if(!$Staff) {
                $_result = Staffs::create(array(
                    "member_id" => $this->_member_id,
                    "boss" => $request->boss
                ));
                if($_result) {
                    throw new \PDOException("申请成功，等待审核", 200);
                } else {
                    throw new \PDOException("申请员工失败，请重新扫码", 402);
                }
            } else {
                if($Staff->deleted_at) {
                    if($Staff->restore()) {
                        $Staff->status = 2;
                        if($Staff->save()) {
                            throw new \PDOException("申请成功，等待审核", 200);
                        } else {
                            throw new \PDOException("申请员工失败，请重新扫码", 402);
                        }
                    } else {
                        throw new \PDOException("申请员工失败，请重新扫码", 402);
                    }
                } else {
                    if($Staff->status == 2) {
                        throw new \PDOException("正在审核中",402);
                    } else {
                        throw new \PDOException("您已经是员工了",402);
                    }
                }
            }
        } catch (\PDOException $e) {
            if($e->getCode() == 200) {
                DB::commit();
            } else {
                DB::rollBack();
            }
            return array("message"=>$e->getMessage(),"code"=>$e->getCode());
        }
    }

    /**
     * 卡券核销
     * @param $request
     */
    private function checkCoupon($request)
    {
        DB::beginTransaction();
        try{
            $_params = array(
                "coupon_id"=>$request->coupon_id,
                "scan_type"=>$request->scan_type,
                "uniqid" => $request->uniqid
            );
            if(!$this->Qrcode->checkParams($_params)) {
                throw new \PDOException("二维码失效", 402);
            }
            $MemberCoupon = MemberCoupon::where("id",$request->coupon_id)
                ->first()->setAppends(['coupon']);
            // 1、检测是不是卡券创建者
            $_owner_member_id = Coupons::where("id",$MemberCoupon->coupon_id)
                ->value("member_id");
            if($this->_member_id != $_owner_member_id) {
                // 2、获取卡券创建者下的员工列表
                $Staff = Staffs::where("bass",$_owner_member_id)
                    ->where("member_id",$this->_member_id)
                    ->where("status",1)
                    ->exists();
                if(!$Staff) {
                    throw new \PDOException("无核销权限",402);
                }
            }
            // 3、验证卡券状态
            if($MemberCoupon->status == 2) {
                throw new \PDOException("卡券已核销",402);
            }
            // 4、卡券是否已经过期
            if($MemberCoupon->past) {
                throw new \PDOException("卡券已过期",402);
            }
            // 5、核销修改卡券状态
            $MemberCoupon->status = 2;
            if($MemberCoupon->save()) {
                throw new \PDOException("核销成功",200);
            } else {
                throw new \PDOException("核销失败，请重试",402);
            }
        }catch (\PDOException $e) {
            if($e->getCode() == 200) {
                DB::commit();
            } else {
                DB::rollBack();
            }
            return array("message"=>$e->getMessage(),"code"=>$e->getCode());
        }
    }

    /**
     * 申请系统员工
     */
    private function applyManage($request)
    {
        try{
            $_params = array(
                "scan_type"=>$request->scan_type,
                "uniqid" => $request->uniqid
            );
            if(!$this->Qrcode->checkParams($_params)) {
                throw new \Exception("二维码失效", 402);
            }
            if(Cache::put('scan_manage_member',Member::find($this->_member_id))) {
                throw new \Exception('扫码成功', 200);
            } else {
                throw new \Exception('扫码失败', 402);
            }
        }catch (\Exception $e) {
            return array("message"=>$e->getMessage(),"code"=>$e->getCode());
        }
    }
}
